package StackAndQueue;

import java.util.ArrayDeque;

public class RemoveDuplicates1047 {
    public static void main(String[] args) {
        System.out.println(removeDuplicates1("abbaaa"));
        char[] s = new char[]{'a','a'};
        System.out.println(new String(s,0,1));

    }
    public static String removeDuplicates(String s) {
        if(s == null){
            return s;
        }
        ArrayDeque<Character> stack = new ArrayDeque<>();
        char[] strArray = s.toCharArray();
        int i = 0;
        while(i < strArray.length){
            if(stack.size() == 0 || strArray[i] != stack.peek()){
                 stack.push(strArray[i]);
             }else{
                 stack.pop();
             }
             i++;
        }
        String str = "";
        //剩余的元素即为不重复的元素
        while (!stack.isEmpty()) {
            str = stack.pop() + str;
        }
        return str;
    }

    public static String removeDuplicates1(String s) {
        char[] ch = s.toCharArray();
        int fast = 0;
        int slow = 0;
        while(fast < s.length()){
            // 直接用fast指针覆盖slow指针的值
            ch[slow] = ch[fast];
            // 遇到前后相同值的，就跳过，即slow指针后退一步，下次循环就可以直接被覆盖掉了
            if(slow > 0 && ch[slow] == ch[slow - 1]){
                slow--;
            }else{
                slow++;
            }
            fast++;
        }
        return new String(ch,0,slow);
    }
}
